//
//  CityViewController.m
//  HappyToday
//
//  Created by Ale (ziming) Lee on 16/8/5.
//  Copyright © 2016年 ziming_lee. All rights reserved.
//

#import "CityViewController.h"
#import "CityModel.h"

@interface CityViewController (){

    NSMutableDictionary *_citiesDic;//所有城市
    NSMutableArray *_hotCitiesArray;//所有热门城市
    NSMutableArray *_nearestArray;//最近的城市
    NSMutableArray *_allKeys;//_citiesDic一共有多少组
    NSArray *_currentAllkeys;//当前一共多少组

}


@end

@implementation CityViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self _loadCityData];

    [self _registerCollectionViewCellAndHeaderView];

    _allKeys = [NSMutableArray arrayWithArray:[[_citiesDic allKeys] sortedArrayUsingSelector:@selector(compare:)]];

    //把两个汉字的分组移动到最前
    //移动热门城市到最前，删除最后一个是当前城市则成为最后一个
    [_allKeys insertObject:[_allKeys lastObject] atIndex:0];
    [_allKeys removeLastObject];
    [_allKeys insertObject:[_allKeys lastObject] atIndex:0];
    [_allKeys removeLastObject];
    _currentAllkeys = _allKeys;

    //谓词搜索----------通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(_textFieldValueDidChange) name:UITextFieldTextDidChangeNotification object:nil];


}

-(void)_textFieldValueDidChange{

    NSString *textString = _textField.text;
    NSString *string = [NSString stringWithFormat:@"self like [C] '*%@*'",textString];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:string];
    /************谓词过滤*********/
    _currentAllkeys = [_allKeys filteredArrayUsingPredicate:predicate];
    [_cityCollectionView reloadData];

}


- (IBAction)BackButtonAction:(UIButton *)sender {

    [self dismissViewControllerAnimated:YES completion:nil];
}
//-(void)_setTitleView{
//
//    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenW, 30+30)];
//    UILabel *title = [[UILabel alloc]initWithFrame:titleView.bounds];
//    title.text = @"城市选择";
//    title.textAlignment = NSTextAlignmentCenter;
//    title.textColor = [UIColor blackColor];
//    [titleView addSubview:title];
//    //    titleView.backgroundColor = [UIColor greenColor];
//
//    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(5, 20, 20, titleView.height/3)];
//    [backBtn setBackgroundImage:[UIImage imageNamed:@"Login_close@3x"] forState:UIControlStateNormal];
//    [backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//    [titleView addSubview:backBtn];
//
//    [self.view addSubview:titleView];
//
//}
//-(void)backBtnAction:(UIButton *)button{
//
//    [self dismissViewControllerAnimated:YES completion:nil];
//
//}
#pragma mark-------加载数据
-(void)_loadCityData{

//--------------------------------
    _citiesDic = [[NSMutableDictionary alloc]initWithCapacity:1];
    _hotCitiesArray = [[NSMutableArray alloc]initWithCapacity:1];
    _nearestArray = [[NSMutableArray alloc]initWithCapacity:1];
//--------------------------------



    //1.根据JSON文件获取到根数据结构
    NSDictionary *rootDataDic = [DataParser jsonObjectFromFileName:@"cities"];
    NSDictionary *inforDic = [rootDataDic objectForKey:@"infor"];
    NSArray *listItems = [inforDic objectForKey:@"listItems"];
    for (NSDictionary *dic in listItems) {

        //每一个城市的信息都存入一个model中
        CityModel *model = [[CityModel alloc]initWithDic:dic];

#pragma mark--------------------------------------------------------------------
        //取出城市的首字母加入到城市数组中
        NSMutableArray *citiesArray = [_citiesDic objectForKey:model.charindex];
#pragma mark--------------------------------------------------------------------

        /*1.***********************添加所有城市到分组中****************************/
        if (citiesArray == nil) {

            NSMutableArray *citiesArray = [[NSMutableArray alloc]initWithCapacity:1];
            [citiesArray addObject:model];
            [_citiesDic setObject:citiesArray forKey:model.charindex];
        }else{

            [citiesArray addObject:model];
            [_citiesDic setObject:citiesArray forKey:model.charindex];

        }
        /*2.***********************添加热门城市到分组中****************************/
        if ([model.level isEqualToString:@"1"]) {
            [_hotCitiesArray addObject:model];
            [_citiesDic setObject:_hotCitiesArray forKey:@"热门城市"];
        }
        /*3.***********************添加当前/最近的城市到分组中**********************/

        if ([model.nodepath isEqualToString:@"0"]) {
            [_nearestArray addObject:model];
            [_citiesDic setObject:_nearestArray forKey:@"当前城市"];
        }

    }
    
    

}
#pragma mark--------注册collectionViewCell
/**********************************************/
-(void)_registerCollectionViewCellAndHeaderView{

    //1.注册单元格
    [_cityCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"city_cell"];
    //2.注册头视图
    [_cityCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"city_header"];


}
/********************定制头视图******************/
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{

    if (kind == UICollectionElementKindSectionHeader) {

        //1.设置头视图的复用
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"city_header" forIndexPath:indexPath];

        //2。设置头视图透明的
        headerView.backgroundColor = [UIColor clearColor];

        #pragma mark-----------------解决复用问题
        for (UIView *view in headerView.subviews) {
            [view removeFromSuperview];

        }

        //3.设置头视图标题
        UILabel *label = [[UILabel alloc]initWithFrame:headerView.bounds];

        /*************************头视图数据加载******************************/
        label.text = [_currentAllkeys objectAtIndex:indexPath.section];
        /*************************头视图数据加载*****************************/

        label.font = [UIFont systemFontOfSize:17];
        label.textColor = [UIColor grayColor];
        [headerView addSubview:label];


        return headerView;

    }
    return nil;
}
/***********UICollectionViewDelegate***********/
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    //一共有多少组

    NSArray *array = [_citiesDic objectForKey:_currentAllkeys[section]];
    return array.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"city_cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.layer.borderColor = [UIColor grayColor].CGColor;
    cell.layer.borderWidth = 0.5;

    #pragma mark----------解决复用问题————————————————————————
    for (UIView *view in cell.contentView.subviews) {

        [view removeFromSuperview];
    }


    /*cell的contentView上添加label*/
    UILabel *label = [[UILabel alloc]initWithFrame:cell.bounds];
//    label.text = @"佛山";

#pragma mark--------------获取城市名字————————————————————————————————
    NSArray *array = [_citiesDic objectForKey:_currentAllkeys[indexPath.section]];
    CityModel *model = [array objectAtIndex:indexPath.row];
    label.text = model.name;
#pragma mark--------------获取城市名字————————————————————————————————

    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor blackColor];
    [cell.contentView addSubview:label];



    return cell;
}
//设置多少组
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{

    return _currentAllkeys.count;

}


#pragma mark----步骤一，实现点击cell跳转回上一页
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    [self dismissViewControllerAnimated:YES completion:nil];

    NSArray *array = [_citiesDic objectForKey:_currentAllkeys[indexPath.section]];
    CityModel *model = [array objectAtIndex:indexPath.row];
    //回调block
    _block(model.name);

}
-(void)chuanzhi:(CityNameBlock)block{

    _block = block;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
